<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Redis\Channel;

/**
 * Class ManyiController
 * @package Pay\Controller
 * bcpay
 */
class BcpayController extends PayController{
    protected $config;
	protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        $this->config['gateway'] .= "/c2cApi/view/orderbuy";

        $base = [
            'businessNo' => $this->config['mch_id'],
            'nonceStr' => date("YmdHis",time()) . mt_rand(10000000,99999999),
            'timestamp' => time(),
            //'apiSecret' => $this->config['signkey'],
        ];
        $data = [];

        switch($this->config['paytype']) {
            case 1:
                $data['payType'] = 'ALIPAY';
                break;
            //支付宝扫码
            case 3:
                $data['payType'] = 'ALIPAY';
                break;
            //支付宝H5
            case 4:
                $data['payType'] = 'ALIPAY';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        $data['assetCode'] = 'USDT';
        $data['money'] = strval($return['amount']);
        $data['state'] = mt_rand(10000,99999);
        $data['outOrderNo'] = $return['orderid'];

        $base['sign'] = $this->getSign($base,$data);

        $base = array_merge($base, $data);



        po_get($this->config['gateway'], $base);
    }

    //加密
    private function getSign($base,$data){
        //echo '<pre/>'; print_r($base); print_r($data);

        $dataJson = array();
        foreach($data as $k => $v){
            if ($v !== null) {
                $dataJson[$k] = $v;
            }
        }

        $dataJson["nonceStr"] = $base['nonceStr'];
        $dataJson["timestamp"] = $base['timestamp'];
        $dataJson["apiSecret"] = $this->config['signkey'];


        ksort($dataJson);  //按数组的键排序;

        //print_r($dataJson);

        //echo '<pre/>'; print_r($dataJson);
        $str = '';
        foreach($dataJson as $k => $v) {
            $str .= "{$k}={$v}&";
        }

        $str = substr($str, 0,-1);

        //echo "str: " . $str . '<br/><br/>';

        return strtoupper(md5($str));
    }

    public function notifyurl(){
        //$this->debug_callback();
        if(!$this->checkip(getIP(),['47.244.138.107','47.52.26.95'])){
            exit("wrong");
        }

        $ret = [
            "code" => "100200",
            "data" => [],
            "msg" => "成功",
        ];

        $p = file_get_contents("php://input");

        //$p = '{"businessNo":"100000996050600010","data":{"msg":"","amount":"43.04000000000000000000","code":"100200","payType":"WECHAT","money":"300.00000000000000000000","price":"6.97000000000000000000","originMoney":"300.00000000000000000000","state":"34598","id":1120575256209002503,"outOrderNo":"2019042314271540484","advertId":"af0d06df9e734dad87ad5e650103d369","callbackType":"callBackBuyAdvert"},"sign":"6D9BFA4E2249CBA1FD63CE4EF05FB3E8","nonceStr":"96943963221404436623633651627826","timestamp":1556005459}';

        $p = json_decode($p,true);
        if(empty($p)){
            $ret['code'] = "-1";
            $ret['msg'] = "数据为空";

            exit(json_encode($ret));
        }

        $ret['data'] = $p['data'];

        //获取订单信息
        $orderid = $p['data']['outOrderNo'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){

            $ret['code'] = "-1";
            $ret['msg'] = "不存在的订单号";

            exit(json_encode($ret));
        }

        //保存回调数据
/*        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            //"pay_orderid_rd"=>$p['trade_no']
        ));*/

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        if($p['data']['code'] !== '100200'){

            $ret['code'] = "-1";
            $ret['msg'] = "支付失败";

            exit(json_encode($ret));
        }

        $sign = $p['sign'];

        $data = $p['data'];
        unset($p['data']);
        $sign2 = $this->getSign($p, $data);

        //echo 'sign: '.$sign."<br/>";
        //echo "sign2:".$sign2."<br/>"; exit;

        if($sign !== $sign2){
            exit("sign_wrong");
        }

        //处理支付
        $this->async($find['pay_orderid'],json_encode($ret));
    }
}